﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Xml.Serialization;

namespace ObjectModel.Utilities
{
    public class DeepCopy
    {
        /// <summary>
        /// Makes a deep copy of the specified object.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="objectToCopy">Object to make a deep copy of.</param>
        /// <returns>Deep copy of the object</returns>
        public static T Copy<T>(T objectToCopy) where T : class
        {

            using (var stream = new MemoryStream())
            {
                var bf = new BinaryFormatter();
                bf.Serialize(stream, objectToCopy);
                stream.Position = 0;
                return (T)bf.Deserialize(stream);
            }
        }

        /// <summary>
        /// Makes a deep copy of the specified object using xml serialization.
        /// </summary>
        public static T XmlCopy<T>(T objectToCopy) where T : class
        {
            using (MemoryStream stream = new MemoryStream())
            {
                XmlSerializer serializer = new XmlSerializer(objectToCopy.GetType());
                serializer.Serialize(stream, objectToCopy);
                stream.Position = 0;
                return (T)serializer.Deserialize(stream);
            }
        }
    }
}
